package com.tanhua.server.service;

import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.PeachblossomVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.PeachblossomApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {
    @Autowired
    private OssTemplate ossTemplate;
    @Reference
    private PeachblossomApi peachblossomApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void sendVoice(MultipartFile soundFile) {
        try {
            String url = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
            System.out.println(url);
            peachblossomApi.saveVoice(url, UserHolder.getUserId());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PeachblossomVo findVoice() {
        String key = "publish_voice_" + UserHolder.getUserId();
        PeachblossomVo peachblossomVo = new PeachblossomVo();
        List<Voice> voicesList = peachblossomApi.findAllVoice();
        for (Voice voice : voicesList) {
            Long radomUserId = RandomUtils.nextLong(1, voicesList.size());
            if (radomUserId != UserHolder.getUserId()) {
                String value=null;
                value = stringRedisTemplate.opsForValue().get(key);
                if (StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(key))) {
                    stringRedisTemplate.opsForValue().set(key, "9", 1, TimeUnit.DAYS);
                } else if (Integer.valueOf(value) > 0) {
                    stringRedisTemplate.delete(key);
                    stringRedisTemplate.opsForValue().set(key, String.valueOf((Integer.valueOf(value)-1)), 1, TimeUnit.DAYS);
                }
                peachblossomVo.setId(radomUserId.intValue());
                peachblossomVo.setSoundUrl(voice.getSoundUrl());
                UserInfo userInfo = userInfoApi.findUserById(radomUserId);
                BeanUtils.copyProperties(userInfo, peachblossomVo);
                if (StringUtils.isEmpty(value)){
                    value="10";
                }
                peachblossomVo.setRemainingTimes(Integer.valueOf(value));
                return peachblossomVo;
            }
        }
        return null;
    }
}
